﻿using Dapper;
using OMG.Fill.Vegetable.Model;
using OMG.Fill.Vegetable.Model.Ent;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OMG.Fill.Vegetable.Service
{
    /// <summary>
    /// 用户角色表T_UserRole通用操作类
    /// </summary>
    public class UserRoleServices:UserRoles
    {
        public Pager<List<UserRoleEntity>> GetPageList(UserRoleQuery query)
        {
            Pager<List<UserRoleEntity>> obj = new Pager<List<UserRoleEntity>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            //if (!string.IsNullOrEmpty(query.GroupCode))
            //{
            //  strWhereSql += "and GroupCode = @GroupCode ";
            //  paramlist.Add("GroupCode", query.GroupCode);
            //}
            string strFromSql = "from dbo.T_UserRole where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = "";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by Id ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<UserRoleEntity>(strSql,paramlist).ToList();
                    obj.total = dbCon.Query<int>(strTotal,paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取用户角色表T_UserRole分页列表失败", ex);
                return obj;
            }
        }


        public ResResult<List<UserRoleItem>> GetRoleList(string userId)
        {
            ResResult<List<UserRoleItem>> obj = new ResResult<List<UserRoleItem>>();
            string strSql = "select * from dbo.T_Role where status='1' order by sort asc";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.model = dbCon.Query<UserRoleItem>(strSql).ToList();
                    for (int i = 0; i < obj.model.Count; i++)
                    {
                        if (CheckUserRole(userId, obj.model[i].Id))
                        {
                            obj.model[i]._checked = true;
                        }
                        else
                        {
                            obj.model[i]._checked = false;
                        }
                    }
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 获取用户角色操作按钮权限列表
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<UserActionItem> GetUserActionList(string userId)
        {
            List<UserActionItem> obj = new List<UserActionItem>();
            string strSql = "select distinct t4.CtrlUrl,t4.ActionCode from T_UserRole t1 ";
            strSql += "inner join T_Role t2 on t2.Id=t1.RoleId ";
            strSql += "inner join T_MenuRole t3 on t3.RoleId=t2.Id ";
            strSql += "inner join T_Menu_Action t4 on t4.Id=t3.ActionId ";
            strSql += "where t1.UserId=@UserId and t3.ActionId!='' ";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj = dbCon.Query<UserActionItem>(strSql, new { UserId = userId }).ToList();
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("获取失败", ex);
                return obj;
            }
        }
        public bool CheckUserRole(string userId, string roleId)
        {
            string strSql = "select count(1) from dbo.T_UserRole where UserId=@UserId and RoleId=@RoleId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    if (dbCon.Query<int>(strSql, new { UserId = userId, RoleId = roleId }).FirstOrDefault() == 1)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public ResResult<int> AddInfo(UserRoleModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.T_UserRole";
            strSql += "(";
            strSql += "Id,";
            strSql += "RoleId,";
            strSql += "UserId)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@RoleId,";
            strSql += "@UserId)";
            string strDel = @"Delete from dbo.T_UserRole where UserId=@UserId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    var trans = dbCon.BeginTransaction();
                    for (int i = 0; i < model.RoleList.Count; i++)
                    {
                        model.RoleList[i].Id = CustomFun.GetGuid();
                    }
                    int delresult = dbCon.Execute(strDel, new { UserId = model.UserId }, trans);
                    int result = dbCon.Execute(strSql, model.RoleList, trans);
                    //提交事务
                    trans.Commit();
                    obj.model = result;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "添加成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("新增用户角色表T_UserRole对象信息失败", ex);
                return obj;
            }
        }
    }
}